import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import os
from .converter import DocxConverter
import json
from .languages import LANGUAGES

class ConverterGUI:
    def __init__(self, root):
        self.root = root
        self.load_language()
        self.root.title(self.lang["title"])
        self.root.minsize(600, 400)
        self.root.geometry("800x600")
        self.converter = DocxConverter()
        self.setup_ui()
        self.setup_language_menu()
    
    def load_language(self):
        """加载语言配置"""
        self.current_lang = "zh_CN"
        try:
            with open('config.json', 'r', encoding='utf-8') as f:
                config = json.load(f)
                self.current_lang = config.get('language', 'zh_CN')
        except:
            pass
        self.lang = LANGUAGES[self.current_lang]
    
    def setup_language_menu(self):
        """设置语言菜单"""
        self.lang_menu = tk.Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label=self.lang["language_menu"], menu=self.lang_menu)
        self.lang_menu.add_command(label=self.lang["chinese"], command=lambda: self.change_language("zh_CN"))
        self.lang_menu.add_command(label=self.lang["english"], command=lambda: self.change_language("en_US"))
    
    def change_language(self, lang_code):
        """切换语言"""
        if lang_code != self.current_lang:
            self.current_lang = lang_code
            self.lang = LANGUAGES[lang_code]
            # 保存语言设置
            with open('config.json', 'w', encoding='utf-8') as f:
                json.dump({'language': lang_code}, f)
            # 刷新界面
            self.refresh_ui()
    
    def refresh_ui(self):
        """刷新界面语言"""
        # 更新窗口标题
        self.root.title(self.lang["title"])
        
        # 更新所有控件的文本
        # 选择文件按钮
        self.select_file_btn.config(text=self.lang["select_files"])
        
        # 输出目录框架
        self.output_frame.config(text=self.lang["output_settings"])
        self.use_original_radio.config(text=self.lang["use_original_dir"])
        self.custom_dir_radio.config(text=self.lang["custom_dir"])
        self.select_dir_btn.config(text=self.lang["select_output_dir"])
        
        # 文件命名框架
        self.naming_frame.config(text=self.lang["naming_settings"])
        self.use_original_name_radio.config(text=self.lang["use_original_name"])
        self.custom_name_radio.config(text=self.lang["custom_name"])
        self.custom_name_label.config(text=self.lang["custom_name_label"])
        
        # 标题选项
        self.title_checkbox.config(text=self.lang["title_option"])
        
        # 转换按钮
        self.convert_btn.config(text=self.lang["start_convert"])
        
        # 文件管理框架
        self.delete_frame.config(text=self.lang["file_management"])
        self.delete_word_btn.config(text=self.lang["delete_word"])
        self.delete_md_btn.config(text=self.lang["delete_md"])
        
        # 文件列表框架
        self.list_frame.config(text=self.lang["selected_files"])
        
        # 语言菜单
        self.lang_menu.entryconfig(0, label=self.lang["chinese"])
        self.lang_menu.entryconfig(1, label=self.lang["english"])
        self.menubar.entryconfig(1, label=self.lang["language_menu"])
    
    def setup_ui(self):
        # 创建菜单栏
        self.menubar = tk.Menu(self.root)
        self.root.config(menu=self.menubar)
        
        # 创建主框架并启用网格权重
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(0, weight=1)
        
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置主框架的网格权重
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        
        # 创建左右分栏
        left_frame = ttk.Frame(main_frame)
        right_frame = ttk.Frame(main_frame)
        left_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 10))
        right_frame.grid(row=0, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 左侧控制面板
        # 选择文件按钮
        self.select_file_btn = ttk.Button(left_frame, text=self.lang["select_files"], command=self.select_files)
        self.select_file_btn.grid(row=0, column=0, pady=10, sticky=(tk.W, tk.E))
        
        # 输出目录选项框架
        self.output_frame = ttk.LabelFrame(left_frame, text=self.lang["output_settings"], padding="10")
        self.output_frame.grid(row=1, column=0, pady=10, sticky=(tk.W, tk.E))
        
        self.output_var = tk.StringVar(value="custom")
        self.use_original_radio = ttk.Radiobutton(self.output_frame, text=self.lang["use_original_dir"], 
                       variable=self.output_var, 
                       value="original",
                       command=self.toggle_output_button)
        self.use_original_radio.grid(row=0, column=0, pady=5)
        
        self.custom_dir_radio = ttk.Radiobutton(self.output_frame, text=self.lang["custom_dir"], 
                       variable=self.output_var,
                       value="custom",
                       command=self.toggle_output_button)
        self.custom_dir_radio.grid(row=1, column=0, pady=5)
        
        # 选择输出目录按钮
        self.select_dir_btn = ttk.Button(self.output_frame, text=self.lang["select_output_dir"], command=self.select_output_dir)
        self.select_dir_btn.grid(row=2, column=0, pady=5, sticky=(tk.W, tk.E))
        
        # 文件命名选项框架
        self.naming_frame = ttk.LabelFrame(left_frame, text=self.lang["naming_settings"], padding="10")
        self.naming_frame.grid(row=3, column=0, pady=10, sticky=(tk.W, tk.E))
        
        self.naming_var = tk.StringVar(value="original")
        self.use_original_name_radio = ttk.Radiobutton(self.naming_frame, text=self.lang["use_original_name"], 
                                                  variable=self.naming_var, value="original")
        self.use_original_name_radio.grid(row=0, column=0, pady=5)
        
        self.custom_name_radio = ttk.Radiobutton(self.naming_frame, text=self.lang["custom_name"], 
                                            variable=self.naming_var, value="custom")
        self.custom_name_radio.grid(row=1, column=0, pady=5)
        
        # 自定义文件名输入框
        name_frame = ttk.Frame(left_frame)
        name_frame.grid(row=4, column=0, pady=10, sticky=(tk.W, tk.E))
        self.custom_name_label = ttk.Label(name_frame, text=self.lang["custom_name_label"])
        self.custom_name_label.grid(row=0, column=0, padx=5)
        self.custom_name = ttk.Entry(name_frame)
        self.custom_name.grid(row=0, column=1, sticky=(tk.W, tk.E))
        name_frame.grid_columnconfigure(1, weight=1)
        
        # 添加标题选项
        title_frame = ttk.Frame(left_frame)
        title_frame.grid(row=5, column=0, pady=10, sticky=(tk.W, tk.E))
        self.add_title_var = tk.BooleanVar(value=False)
        self.title_checkbox = ttk.Checkbutton(title_frame, text=self.lang["title_option"], 
                                         variable=self.add_title_var)
        self.title_checkbox.grid(row=0, column=0, sticky=tk.W)
        
        # 转换按钮
        self.convert_btn = ttk.Button(left_frame, text=self.lang["start_convert"], command=self.convert_files)
        self.convert_btn.grid(row=6, column=0, pady=20, sticky=(tk.W, tk.E))
        
        # 删除按钮框架
        self.delete_frame = ttk.LabelFrame(left_frame, text=self.lang["file_management"], padding="10")
        self.delete_frame.grid(row=7, column=0, pady=10, sticky=(tk.W, tk.E))
        
        # 删除按钮
        delete_btns_frame = ttk.Frame(self.delete_frame)
        delete_btns_frame.grid(row=0, column=0, pady=5)
        delete_btns_frame.grid_columnconfigure(0, weight=1)
        delete_btns_frame.grid_columnconfigure(1, weight=1)
        
        self.delete_word_btn = ttk.Button(delete_btns_frame, text=self.lang["delete_word"], 
                                     command=self.delete_word_files)
        self.delete_word_btn.grid(row=0, column=0, padx=5)
        
        self.delete_md_btn = ttk.Button(delete_btns_frame, text=self.lang["delete_md"], 
                                   command=self.delete_md_files)
        self.delete_md_btn.grid(row=0, column=1, padx=5)
        
        # 右侧文件列表
        self.list_frame = ttk.LabelFrame(right_frame, text=self.lang["selected_files"], padding="10")
        self.list_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        right_frame.grid_columnconfigure(0, weight=1)
        right_frame.grid_rowconfigure(0, weight=1)
        
        # 创建文件列表显示
        self.file_list = tk.Listbox(self.list_frame, width=50, height=15)
        scrollbar = ttk.Scrollbar(self.list_frame, orient="vertical", command=self.file_list.yview)
        self.file_list.configure(yscrollcommand=scrollbar.set)
        
        self.file_list.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        self.list_frame.grid_columnconfigure(0, weight=1)
        self.list_frame.grid_rowconfigure(0, weight=1)
        
    def toggle_output_button(self):
        """根据选择启用或禁用输出目录按钮"""
        if self.output_var.get() == "original":
            self.select_dir_btn.state(['disabled'])
            self.output_dir = None  # 清除之前选择的输出目录
        else:
            self.select_dir_btn.state(['!disabled'])
    
    def select_files(self):
        self.files = filedialog.askopenfilenames(
            filetypes=[("Word文档", "*.docx")],
            title=self.lang["select_files"]
        )
        # 更新文件列表显示
        self.file_list.delete(0, tk.END)
        for file in self.files:
            self.file_list.insert(tk.END, os.path.basename(file))
        self.status_label.config(text=self.lang["files_selected"].format(len(self.files)))
        
    def select_output_dir(self):
        self.output_dir = filedialog.askdirectory(title=self.lang["select_output_dir"])
        if self.output_dir:
            self.status_label.config(text=self.lang["output_dir_set"].format(self.output_dir))
        
    def convert_files(self):
        if not hasattr(self, 'files'):
            self.status_label.config(text=self.lang["no_files"])
            return
            
        if self.output_var.get() == "custom" and not hasattr(self, 'output_dir'):
            self.status_label.config(text=self.lang["no_output_dir"])
            return
            
        total = len(self.files)
        for i, file_path in enumerate(self.files, 1):
            # 确定输出目录
            if self.output_var.get() == "original":
                output_dir = os.path.dirname(file_path)
            else:
                output_dir = self.output_dir
            
            content = self.converter.convert_docx_to_md(file_path, self.add_title_var.get())
            
            if self.naming_var.get() == "original":
                output_name = os.path.splitext(os.path.basename(file_path))[0] + '.md'
            else:
                custom_name = self.custom_name.get()
                if not custom_name:
                    self.status_label.config(text=self.lang["no_custom_name"])
                    return
                if total > 1:
                    output_name = f"{custom_name}_{i}.md"
                else:
                    output_name = custom_name + '.md'
            
            output_path = os.path.join(output_dir, output_name)
            self.converter.save_to_md(output_path, content)
            self.status_label.config(text=self.lang["converting"].format(i, total))
            self.root.update()
        
        self.status_label.config(text=self.lang["convert_complete"]) 
    
    def confirm_delete(self, message):
        """显示删除确认对话框"""
        return tk.messagebox.askyesno("确认删除", message, icon='warning')
    
    def delete_word_files(self):
        """删除所选的Word文档"""
        if not hasattr(self, 'files') or not self.files:
            self.status_label.config(text=self.lang["no_word_files"])
            return
        
        if not self.confirm_delete(self.lang["confirm_delete_word"]):
            return
        
        deleted_count = 0
        for file_path in self.files:
            try:
                os.remove(file_path)
                deleted_count += 1
            except Exception as e:
                print(f"删除文件失败: {file_path}\n错误: {e}")
        
        # 清空文件列表
        self.file_list.delete(0, tk.END)
        self.files = ()
        self.status_label.config(text=self.lang["deleted_word"].format(deleted_count))
    
    def delete_md_files(self):
        """删除生成的Markdown文档"""
        if not hasattr(self, 'files') or not self.files:
            self.status_label.config(text=self.lang["no_md_files"])
            return
        
        if not self.confirm_delete(self.lang["confirm_delete_md"]):
            return
        
        deleted_count = 0
        for file_path in self.files:
            try:
                # 根据当前设置确定md文件路径
                if self.output_var.get() == "original":
                    output_dir = os.path.dirname(file_path)
                else:
                    if not hasattr(self, 'output_dir'):
                        continue
                    output_dir = self.output_dir
                
                # 确定md文件名
                if self.naming_var.get() == "original":
                    md_name = os.path.splitext(os.path.basename(file_path))[0] + '.md'
                else:
                    custom_name = self.custom_name.get()
                    if not custom_name:
                        continue
                    if len(self.files) > 1:
                        md_name = f"{custom_name}_{self.files.index(file_path)+1}.md"
                    else:
                        md_name = custom_name + '.md'
                
                md_path = os.path.join(output_dir, md_name)
                if os.path.exists(md_path):
                    os.remove(md_path)
                    deleted_count += 1
            except Exception as e:
                print(f"删除文件失败: {md_path}\n错误: {e}")
        
        self.status_label.config(text=self.lang["deleted_md"].format(deleted_count)) 